package com.dfdchem.imd.kaiwu.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.base.BaseActivity;
import com.dfdchem.imd.kaiwu.adapter.NewsAdapter;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.interfaces.OnHttpResponseListener;
import com.dfdchem.imd.kaiwu.interfaces.RecyclerItemClickListener;
import com.dfdchem.imd.kaiwu.manager.DataManager;
import com.dfdchem.imd.kaiwu.manager.IntranetManager;
import com.dfdchem.imd.kaiwu.model.AppArticle;
import com.dfdchem.imd.kaiwu.model.RespList;
import com.dfdchem.imd.kaiwu.util.JSON;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.RequestUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.List;


/**
 * 新闻公告
 */
@Route(path = RouterPath.NEWS_ACTIVITY)
public class NewsActivity extends BaseActivity implements View.OnClickListener, OnRefreshListener, OnHttpResponseListener, OnLoadMoreListener {

    private static final String TAG = "NewsActivity";

    private RecyclerView recyclerView;
    private NewsAdapter newsAdapter;
    private LinearLayoutManager layoutManager;

    private RefreshLayout refreshLayout;

    public static final int request_code_get_article_list = 1;

    private int request_page = 1;
    private int request_limit = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);

        initView();
        initData();
        initEvent();
    }

    @Override
    public void initView() {
        recyclerView = findView(R.id.recycler_view);

        refreshLayout = findViewById(R.id.refreshLayout);

        recyclerView.setHasFixedSize(true);

        // use a linear layout manager
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        // specify an adapter (see also next example)
        newsAdapter = new NewsAdapter(null);
        recyclerView.setAdapter(newsAdapter);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
                layoutManager.getOrientation());
        dividerItemDecoration.setDrawable(getDrawable(R.drawable.profile_list_divider));
        recyclerView.addItemDecoration(dividerItemDecoration);

    }

    @Override
    public void initData() {
        loadData();
    }

    private void loadData(){
        runThread(TAG + "getArticleList", new Runnable() {
            @Override
            public void run() {
                RequestUtil.getArticleList(request_page, request_limit, request_code_get_article_list, NewsActivity.this);
            }
        });

        // 设置默认的超时，防止卡住
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (refreshLayout.getState() == RefreshState.Refreshing) {
                    refreshLayout.finishRefresh(250);
                } else if (refreshLayout.getState() == RefreshState.Loading) {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        },10000); // 延时10秒
    }

    @Override
    public void initEvent() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);

        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(context, recyclerView ,new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {
                        AppArticle appArticle = newsAdapter.getNews().get(position);
                        String url = IntranetManager.URL_BASE_API +  "/La/AppArticle/Detail/0/0/0/" + appArticle.getId();
                        ARouter.getInstance()
                                .build(DataManager.getInstance().isX5() ? RouterPath.WEB_VIEW_X5_ACTIVITY : RouterPath.WEB_VIEW_ACTIVITY)
                                .withString("url", url)
                                .navigation(NewsActivity.this);
                    }

                    @Override public void onLongItemClick(View view, int position) {
                        Log.d(TAG, "addOnItemTouchListener onLongItemClick");
                    }
                })
        );
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.iv_back:
                onBackPressed();
                break;
        }
    }

    @Override
    public void onReturnClick(View v) {
        enterAnim = R.anim.left_push_in;
        exitAnim = R.anim.right_push_out;
        this.finish();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        Log.d(TAG, "onRefresh");
        request_page = 1;
        refreshLayout.setEnableLoadMore(true);
        loadData();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        Log.d(TAG, "onLoadMore");
        request_page ++;
        loadData();
    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
        Log.d(TAG, "onHttpResponse requestCode:" + requestCode + " resultJson:" + resultJson);
        RespList<AppArticle> resp = JSON.parseRespList(resultJson, AppArticle.class);
        Log.d(TAG, "resp:" + resp);
        Log.d(TAG, "resp:" + JSON.toJSONString(resp));
        if (resp == null || resp.getCode() != 200 ) {
            Toast.makeText(this, resp != null ? resp.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(250);
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
            return;
        }
        List<AppArticle> articles = resp.getData();
        Log.d(TAG, "articles:" + articles.size());
        if (articles == null) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(250);
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
            Toast.makeText(this, "解析异常", Toast.LENGTH_LONG).show();
            return;
        }

        request_page = resp.getPage();
        request_limit = resp.getLimit();

        if (refreshLayout.getState() == RefreshState.None || refreshLayout.getState() == RefreshState.Refreshing) {
            if (articles.size() > 0) {
                newsAdapter.setNews(articles);
            }
            refreshLayout.finishRefresh(250);
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            if (articles.size() > 0) {
                List<AppArticle> news = newsAdapter.getNews();
                if (news != null) {
                    news.addAll(articles);
                } else {
                    news = articles;
                }
                newsAdapter.setNews(news);
            }
            if (articles.size() == 0 && request_page * request_limit >= resp.getRecordsTotal()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(250);
            }
        }

        if (articles.size() > 0) {
            newsAdapter.notifyDataSetChanged();
        }
    }
}
